package com.ruoyi.web.controller.business.goods.factory;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.business.base.JoLambdaQW;
import com.ruoyi.business.base.PageParam;
import com.ruoyi.business.goods.domain.JbProduct;
import com.ruoyi.business.goods.service.JbProductService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.controller.system.factory.SysDataScopeFactory;
import com.ruoyi.web.controller.system.factory.SysDictFactory;
import com.ruoyi.web.core.JoController;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 业务 产品工厂
 *
 * @author Jyl
 */
@Component
public class JbProductFactory extends JoController
{

    @Getter
    @Autowired
    private JbProductService jbProductService;
    @Autowired
    private SysDictFactory sysDictFactory;
    @Autowired
    private JbProductClassifyFactory jbProductClassifyFactory;
    @Autowired
    private JbCropVarietyFactory jbCropVarietyFactory;
    @Autowired
    private JbCommodityFactory jbCommodityFactory;
    @Autowired
    private SysDataScopeFactory sysDataScopeFactory;

    /**
     * 构建 产品查询对象
     *
     * @param page      分页对象
     * @param jbProduct 产品对象
     * @return 产品查询对象
     */
    public JoLambdaQW<JbProduct> buildQW(PageParam page, JbProduct jbProduct)
    {

        //根据部门销售渠道查询
        String channel = getUser().getDept().getChannel();
        if (StrUtil.isNotEmpty(jbProduct.getSalesChannel()))
        {//根据前端传入销售渠道查询
            channel = jbProduct.getSalesChannel();
        }
        JoLambdaQW<JbProduct> select = new JoLambdaQW<JbProduct>();

        select.lambda()
                .eq(StringUtils.isNotNull(jbProduct.getClassifyId()), JbProduct::getClassifyId,
                        jbProduct.getClassifyId())
                .and(StringUtils.isNotEmpty(page.getKeyword()), e -> e
                        .like(JbProduct::getProductName, page.getKeyword())
                        .or().like(JbProduct::getBrandName, page.getKeyword())
                        .or().like(JbProduct::getProductCode, page.getKeyword()))
                .eq(StringUtils.isNotEmpty(jbProduct.getDosageForm()), JbProduct::getDosageForm,
                        jbProduct.getDosageForm())
                .like(StringUtils.isNotEmpty(channel), JbProduct::getSalesChannel, channel)//销售渠道
//                .in(ObjectUtil.isNotEmpty(ids), JbProduct::getCreateBy, ids)//数据权限过滤
                .eq(StringUtils.isNotEmpty(jbProduct.getToxicity()), JbProduct::getToxicity, jbProduct.getToxicity())

                .orderByDesc(JbProduct::getId);

        select.buildColumn(JbProduct.class)
                .reflection(
                        "jb_crop_variety",
                        "crop_name",
                        "recommended_crops",
                        "recommended_crops_name"
                ).reflectionDict(
                        "bus_target",
                        "recommended_targets",
                        "recommended_targets_name"
                );
        return select;
    }

    /**
     * 导入处理
     *
     * @param list 导入数据
     * @return 导入结果
     */
    public boolean importData(List<JbProduct> list)
    {
        //产品属性 bus_product_type
        //产品类别 bus_product_category
        //产品分类 分类对象 jbProductClassifyFactory
        //毒性 bus_toxicity
        //剂型 bus_sosage_form
        //含量单位 bus_active_ingredient_content
        //防治对象 bus_control_object
        //施用方式 bus_application_mode
        //推荐适用作物 作物表  jbCropVarietyFactory
        //推荐适用标靶 bus_target
        //销售渠道 bus_channel
        Map<String, Long> busClassify = jbProductClassifyFactory.dict(0L);
        Map<String, Long> busCropVariety = jbCropVarietyFactory.dict();
        Map<String, String> busToxicity = sysDictFactory.dict("bus_toxicity");
        Map<String, String> busApplicationMode = sysDictFactory.dict("bus_application_mode");
        Map<String, String> busSosageForm = sysDictFactory.dict("bus_sosage_form");
        Map<String, String> busActiveIngredientContent = sysDictFactory.dict("bus_active_ingredient_content");
        Map<String, String> busProductCategory = sysDictFactory.dict("bus_product_category");
        Map<String, String> busProductType = sysDictFactory.dict("bus_product_type");
        Map<String, String> busChannel = sysDictFactory.dict("bus_channel");
        Map<String, String> busCropLocation = sysDictFactory.dict("bus_crop_location");
        Map<String, String> busControlObject = sysDictFactory.dict("bus_control_object");
        Map<String, String> busTarget = sysDictFactory.dict("bus_target");
        for (JbProduct jbProduct : list)
        {
            jbProduct.setStatus("0");
            //1含量单位
            jbProduct.setActiveIngredientUnit1(
                    dict(jbProduct.getActiveIngredientUnit1(), busActiveIngredientContent)
            );
            //2含量单位
            jbProduct.setActiveIngredientUnit2(
                    dict(jbProduct.getActiveIngredientUnit2(), busActiveIngredientContent)
            );
            //3含量单位
            jbProduct.setActiveIngredientUnit3(
                    dict(jbProduct.getActiveIngredientUnit3(), busActiveIngredientContent)
            );
            //产品属性
            jbProduct.setProductType(dict(jbProduct.getProductType(), busProductType));
        }
        return jbProductService.saveBatch(list);
    }

    public String dict(String unit, Map<String, String> map)
    {
        return StrUtil.isNotEmpty(unit) ? (map.containsKey(unit) ? map.get(unit) : "") : "";
    }

    /**
     * 更新产品
     *
     * @param jbProduct 产品对象
     * @return 执行状态
     */
    @Transactional
    public boolean edit(JbProduct jbProduct)
    {
        isNotNullByName(jbProduct.getProductName(), jbProduct.getId());
        //更新产品
        jbProductService.updateById(jbProduct);
        //更新商品
        jbCommodityFactory.updateProduct(jbProduct);
        return true;
    }

    /**
     * 检查 产品名称是否重复
     *
     * @param name 产品名称
     * @return 查询结果
     */
    public boolean isNotNullByName(String name, Long id)
    {
        List<JbProduct> list = jbProductService.list(new LambdaQueryWrapper<JbProduct>()
                .eq(JbProduct::getProductName, name)
                .ne(ObjectUtil.isNotEmpty(id), JbProduct::getId, id)
        );
        if (!list.isEmpty())
        {
            throw new ServiceException("已存在相同名称的产品");
        }

        return true;
    }

    /**
     * 删除 产品 并通知 商品删除
     *
     * @param ids 产品id集合
     * @return 执行结果
     */
    @Transactional
    public Boolean removeByIds(List<Long> ids)
    {
        if (!jbProductService.removeByIds(ids))
        {
            throw new ServiceException("删除产品失败");
        }
        jbCommodityFactory.deleteProductRelated(ids);
        return true;
    }

}
